package com.mavenq.fly.test.suanf;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class TopK {

    public static int[] topKFrequent(int[] nums, int k) {
        if(nums.length == 0){
            return nums;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                map.put(nums[i], map.get(nums[i]) + 1);
            } else {
                map.put(nums[i], 1);
            }
        }
        PriorityQueue<Integer> queue = new PriorityQueue<>(k);
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            Integer value = entry.getValue();
            queue.add(value);
        }

        for (int i = 0; i < k; i++) {
            nums[i] = queue.poll();
        }
        return nums;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1,1,1,2,2,3};
        topKFrequent(nums, 2);
    }
}
